package com.yjc.spring.boot.listener;

import com.yjc.manager.holder.ClassHolder;
import com.yjc.spring.boot.context.DynamicLoadSpringContext;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.Map;

public class DynamicClassUnloadListener implements ApplicationListener<ContextClosedEvent> {


    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) DynamicLoadSpringContext.getInstance().getContext();
        ClassHolder classHolder = ClassHolder.getInstance();
        Map<String, Map<Class<?>, Class<?>>> jarInterfaceMap = classHolder.getJarInterfaceMap();
        for (Map.Entry<String, Map<Class<?>, Class<?>>> jarEntry : jarInterfaceMap.entrySet()) {
            String jarName = jarEntry.getKey();
            for (Map.Entry<Class<?>, Class<?>> interfaceClassEntry : jarEntry.getValue().entrySet()) {
                Class<?> interfaceClass = interfaceClassEntry.getKey();
                String beanName = getBeanName(jarName, interfaceClass);
                Object bean = beanFactory.getBean(beanName);
                beanFactory.destroyBean(beanName,bean);
                beanFactory.removeBeanDefinition(beanName);
            }
        }
        classHolder.unload(null);
    }

    private String getBeanName(String jarName,Class<?> interfaceClass){
        return jarName + "." + interfaceClass.getName();
    }
}
